package com.ttbj.ftp.client;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;
import org.apache.poi.util.ArrayUtil;

import com.ttbj.ftp.core.FTPClientPool;
import com.ttbj.ftp.util.ByteUtil;
import com.ttbj.util.Assert;

/**
 * ftp客户端辅助bean
 * 
 * @author jelly
 *
 */
public class FTPClientHelper {
	private static Logger logger = Logger.getLogger(FTPClientHelper.class);

	private FTPClientPool ftpClientPool;

	public void setFtpClientPool(FTPClientPool ftpClientPool) {
		this.ftpClientPool = ftpClientPool;
	}

	/**
	 * 下载remote文件流
	 * 
	 * @param remote
	 *            远程文件
	 * @return 字节数据
	 * @throws Exception
	 */
	public byte[] retrieveFileStream(String remote) throws Exception {
		FTPClient client = null;
		InputStream in = null;
		try {
			long start = System.currentTimeMillis();
			client = ftpClientPool.borrowObject();
			in = client.retrieveFileStream(remote);
			long end = System.currentTimeMillis();
			System.out.println("ftp下载耗时(毫秒):" + (end - start));
			if (in != null) {
				return ByteUtil.inputStreamToByteArray(in);
			} else {
				return new byte[0];
			}
		} catch (Exception e) {
			logger.error("获取ftp下载流异常", e);
		} finally {
			if (in != null) {
				in.close();
			}
			if (client != null) {
				client.logout();
				client.disconnect();
			}
			ftpClientPool.returnObject(client);
		}
		return null;
	}

	/**
	 * 创建目录 单个不可递归
	 * 
	 * @param pathname
	 *            目录名称
	 * @return
	 * @throws Exception
	 */
	public boolean makeDirectory(String pathname) throws Exception {
		FTPClient client = null;
		try {
			client = ftpClientPool.borrowObject();
			return client.makeDirectory(pathname);
		} catch (Exception e) {
			logger.error("创建目录失败", e);
			throw e;
		} finally {
			ftpClientPool.returnObject(client);
		}
	}

	/**
	 * 递归遍历目录下面指定的文件名
	 * 
	 * @param pathName
	 *            需要遍历的目录，必须以"/"开始和结束
	 * @param ext
	 *            文件的扩展名
	 * @throws Exception
	 */
	public List<String> list(String pathName) throws Exception {
		FTPClient client = null;
		try {
			client = ftpClientPool.borrowObject();
			FTPFile[] listFiles = client.listFiles(pathName);
			if (listFiles != null && listFiles.length > 0) {
				List<FTPFile> asList = Arrays.asList(listFiles);
				List<String> nameList = new ArrayList<String>();
				asList.stream().forEach(file -> nameList.add(pathName + "/" + file.getName()));
				return nameList;
			}
		} catch (Exception e) {
			logger.error("创建目录失败", e);
			throw e;
		} finally {
			ftpClientPool.returnObject(client);
		}
		return null;
	}

	public boolean removeDir(String pathName) throws Exception {
		List<String> list = list(pathName);
		if (Assert.isEmpty(list)) {
			return false;
		}
		for (String pathname : list) {
			deleteFile(pathname);
		}
		removeDirectory(pathName);
		return true ;
	}

	private void cOrMDir(String pathName) throws Exception {
		FTPClient client = null;
		try {
			client = ftpClientPool.borrowObject();
			if (!client.changeWorkingDirectory(pathName)) {
				boolean makeDirectory = client.makeDirectory(pathName); // 创建成功返回true，失败（已存在）返回false
				System.out.println("创建成功返回true，失败（已存在）返回false ---" + makeDirectory);
				boolean changeWorkingDirectory = client.changeWorkingDirectory(pathName); // 切换成返回true，失败（不存在）返回false
				System.out.println("切换成返回true，失败（不存在）返回false--" + changeWorkingDirectory);
			}
		} catch (Exception e) {
			logger.error("创建目录失败", e);
			throw e;
		} finally {
			ftpClientPool.returnObject(client);
		}
	}

	public void changeOrMakeDirectory(String pathName) throws Exception {
		String[] split = pathName.split("/");
		String file = "";
		for (String f : split) {
			file = file + "/" + f;
			cOrMDir(file);
		}
	}

	/**
	 * 删除目录，单个不可递归
	 * 
	 * @param pathname
	 * @return
	 * @throws IOException
	 */
	public boolean removeDirectory(String pathname) throws Exception {
		FTPClient client = null;
		try {
			client = ftpClientPool.borrowObject();
			return client.removeDirectory(pathname);
		} catch (Exception e) {
			logger.error("删除目录失败", e);
			throw e;
		} finally {
			ftpClientPool.returnObject(client);
		}
	}

	/**
	 * 删除文件 单个 ，不可递归
	 * 
	 * @param pathname
	 * @return
	 * @throws Exception
	 */
	public boolean deleteFile(String pathname) throws Exception {
		FTPClient client = null;
		try {
			client = ftpClientPool.borrowObject();
			return client.deleteFile(pathname);
		} catch (Exception e) {
			logger.error("创建文件失败", e);
			throw e;
		} finally {
			ftpClientPool.returnObject(client);
		}
	}

	/**
	 * 上传文件
	 * 
	 * @param remote
	 * @param local
	 * @return
	 * @throws Exception
	 */
	public boolean storeFile(String remote, InputStream local) throws Exception {
		FTPClient client = null;
		try {
			client = ftpClientPool.borrowObject();
			return client.storeFile(remote, local);
		} catch (Exception e) {
			logger.error("上传文件失败", e);
			throw e;
		} finally {
			ftpClientPool.returnObject(client);
		}
	}

}
